var roleVoiceMp3;
var EFxiu = new Audio('qa/9411.mp3');
var EFda = new Audio('qa/9411.mp3');
var vc0 = new Audio('ques/0/tucao.mp3');
var vc1 = new Audio('ques/0/shuaide.mp3');
var vc2 = new Audio('ques/1/tansuan.mp3');
var vc3 = new Audio('ques/1/dongtian.mp3');
var vc4 = new Audio('ques/1/hentian.mp3');
function popup(id, name) {
    $('#match-container').show();
    $('#match-popup').show();
    $('#match-popup').width($(window).width());
    $('#match-popup').height($(window).height());
    $('#match-container .match-photo-op').attr('src', 'ques/' + id + '/' + id + '.jpg?2017111616');
    $('#match-container .match-tit').html(name);
    $('.voice-play').hide();
    $('#chat-open').attr('isclick', 'none');
    $('#chat-open').addClass('rotate-shack')
}

/*返回查看奖品*/
function bankJiangPin(){
	window.location.href = "/home/jiangping.html";
	
}

//抽奖
function choujiang(){
	var is_user = 1;
	var count = localStorage.getItem("choujiangCount"); 
	if( count <= 0){
		layer.open({
			content: "<!DOCTYPE><html>	<head>		<meta charset='utf-8'>		<meta name='viewport' content='width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0'>	</head>	<style>		.jiangCon{			margin:0 auto;		}		img{			max-width:100%;			margin:0 auto;			text-align:center;		}		.jiang,.jinlang,.chakan,.count{			    text-align: center;		}	</style>	<body>		<div class='jiangCon' >			<div class='jiang' style='padding-top:2rem;'>				很遗憾！			</div>			<div class='jiang' style='padding: 2rem 0;'>				谢谢参与			</div>			<div class='count'>				你还有<span style='color:red;font-size:1.2rem;font-weight:bold;padding:0 0.2rem;'>0</span>次机会			</div>			<div class='count' style='padding:2rem;'>				请点击空白页面返回继续点击抽奖			</div>						<div class='jinlang'>				<button  onclick='bankJiangPin()' style='width:50%;height:2.5rem;border:1px solid #ccc;background-color:blue;border-radius:1rem;color:#fff;'>点击查看我的奖品</button>			</div>		</div>	</body></html>"
			
		  });
		return;
	}
	var loding = layer.open({
		type: 2
		,content: '加载中'
	  });
	$.ajax({
		url:'/home/choujiang',
		type:'post',
		dataType:'json',
		data:{is_user:is_user},
		success:function( data ){
			layer.close(loding);
			
			if( data.code == 0 || data.code == 2 ){
					if( data.data.label == 4 ){
						var tishi = "很遗憾！";
					}else{
						var tishi = "恭喜你抽到了";
					}
					if( count > 1 ){
						var newCount = count - 1;
						localStorage.setItem("choujiangCount",newCount);
						if( newCount == 2 ){
							layer.open({
								content: "<!DOCTYPE><html>	<head>		<meta charset='utf-8'>		<meta name='viewport' content='width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0'>	</head>	<style>		.jiangCon{			margin:0 auto;		}		img{			max-width:100%;			margin:0 auto;			text-align:center;		}		.jiang,.jinlang,.chakan,.count{			    text-align: center;		}	</style>	<body>		<div class='jiangCon' >			<div class='jiang' style='padding-top:2rem;'>				"+tishi+"			</div>			<div class='jiang' style='padding: 2rem 0;'>				"+data.data.name+"			</div>			<div class='count'>				你还有<span style='color:red;font-size:1.2rem;font-weight:bold;padding:0 0.2rem;'>"+newCount+"</span>次机会			</div>			<div class='count' style='padding:2rem;'>				请点击空白页面返回继续点击抽奖			</div>						<div class='jinlang'>				<button  onclick='bankJiangPin()' style='width:50%;height:2.5rem;border:1px solid #ccc;background-color:blue;border-radius:1rem;color:#fff;'>点击查看我的奖品</button>			</div>		</div>	</body></html>"
								
							  });
						}else if( newCount = 1 ){
							layer.open({
								content: "<!DOCTYPE><html>	<head>		<meta charset='utf-8'>		<meta name='viewport' content='width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0'>	</head>	<style>		.jiangCon{			margin:0 auto;		}		img{			max-width:100%;			margin:0 auto;			text-align:center;		}		.jiang,.jinlang,.chakan,.count{			    text-align: center;		}	</style>	<body>		<div class='jiangCon' >			<div class='jiang' style='padding-top:2rem;'>				"+tishi+"			</div>			<div class='jiang' style='padding: 2rem 0;'>				"+data.data.name+"			</div>			<div class='count'>				你还有<span style='color:red;font-size:1.2rem;font-weight:bold;padding:0 0.2rem;'>"+newCount+"</span>次机会			</div>			<div class='count' style='padding:2rem;'>				请点击空白页面返回继续点击抽奖			</div>						<div class='jinlang'>				<button  onclick='bankJiangPin()' style='width:50%;height:2.5rem;border:1px solid #ccc;background-color:blue;border-radius:1rem;color:#fff;'>点击查看我的奖品</button>			</div>		</div>	</body></html>"
								
							  });
						}
						
				
				}else{
					//否则没有抽奖次数
					localStorage.setItem("choujiangCount",0);
					layer.open({
								content: "<!DOCTYPE><html>	<head>		<meta charset='utf-8'>		<meta name='viewport' content='width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0'>	</head>	<style>		.jiangCon{			margin:0 auto;		}		img{			max-width:100%;			margin:0 auto;			text-align:center;		}		.jiang,.jinlang,.chakan,.count{			    text-align: center;		}	</style>	<body>		<div class='jiangCon' >			<div class='jiang' style='padding-top:2rem;'>				"+tishi+"			</div>			<div class='jiang' style='padding: 2rem 0;'>				"+data.data.name+"			</div>			<div class='count'>				你还有<span style='color:red;font-size:1.2rem;font-weight:bold;padding:0 0.2rem;'>0</span>次机会			</div>			<div class='count' style='padding:2rem;'>				请点击空白页面返回继续点击抽奖			</div>						<div class='jinlang'>				<button  onclick='bankJiangPin()' style='width:50%;height:2.5rem;border:1px solid #ccc;background-color:blue;border-radius:1rem;color:#fff;'>点击查看我的奖品</button>			</div>		</div>	</body></html>"
								
					});
				}
			}else{
				//layer.alert(data.message)
				layer.open({
					content: data.message
					,btn: '我知道了'
				  });
			}
		}
		
	})
	
}



//抽奖
function choujiang2(){
	var is_user = 1;
	var count = localStorage.getItem("choujiangCount"); 
	if( count <= 0){
		layer.open({
			content: "<!DOCTYPE><html>	<head>		<meta charset='utf-8'>		<meta name='viewport' content='width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0'>	</head>	<style>	 .layui-m-layercont{padding:0 !important;}	.jiangCon{	background:url('/static/home/img/tan/back.png') no-repeat center center fixed;background-size: cover;		margin:0 auto;		}		img{			max-width:100%;			margin:0 auto;			text-align:center;		}		.jiang,.jinlang,.chakan{			    text-align: center;		}	</style>	<body>	<div class='jiangCon'>			<div class='count' style='padding-top:2rem;'>				<img src='/static/home/img/tan/zone.png'>			</div>			<div class='jiang' style='padding: 2rem 0;'>				<img src='/static/home/img/tan/jiang4.png'>			</div>			<div class='jinlang'>				<img src='/static/home/img/tan/jinlangbutton.png' onclick='bankJiangPin()'>			</div>			<div class='chakan' style='padding:1rem 0 2rem;'>				<img src='/static/home/img/tan/show.png'>			</div>		</div>	</body></html>"
			
		  });
		return;
	}
	var loding = layer.open({
		type: 2
		,content: '加载中'
	  });
	$.ajax({
		url:'/home/choujiang',
		type:'post',
		dataType:'json',
		data:{is_user:is_user},
		success:function( data ){
			layer.close(loding);
			
			if( data.code == 0 || data.code == 2 ){
					var jiangImg = '/static/home/img/tan/jiang4.png';
					switch( data.data.label ){
						case '1':
							jiangImg = '/static/home/img/tan/jiang1.png';
							break;
						case '2':
							jiangImg = '/static/home/img/tan/jiang2.png';
							break;
						case '3':
							jiangImg = '/static/home/img/tan/jiang3.png';
							break;
						case '4':
							jiangImg = '/static/home/img/tan/jiang4.png';
							break;
						case '5':
							jiangImg = '/static/home/img/tan/jiang5.png';
							break;
						case '6':
							jiangImg = '/static/home/img/tan/jiang6.png';
							break;
						case '7':
							jiangImg = '/static/home/img/tan/jiang7.png';
							break;
						default:
							jiangImg = '/static/home/img/tan/jiang4.png';
							break;
					} 
					if( count > 1 ){
						var newCount = count - 1;
						localStorage.setItem("choujiangCount",newCount);
						if( newCount == 2 ){
							layer.open({
								content: "<!DOCTYPE><html>	<head>		<meta charset='utf-8'>		<meta name='viewport' content='width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0'>	</head>	<style>	 .layui-m-layercont{padding:0 !important;}	.jiangCon{	background:url('/static/home/img/tan/back.png') no-repeat center center fixed;background-size: cover;		margin:0 auto;		}		img{			max-width:100%;			margin:0 auto;			text-align:center;		}		.jiang,.jinlang,.chakan{			    text-align: center;		}	</style>	<body>		<div class='jiangCon'>			<div class='count' style='padding-top:2rem;'>				<img src='/static/home/img/tan/two.png'>			</div>			<div class='jiang' style='padding: 2rem 0;'>				<img src='"+jiangImg+"'>			</div>			<div class='jinlang'>				<img src='/static/home/img/tan/jinlangbutton.png' onclick='bankJiangPin()'>			</div>			<div class='chakan' style='padding:1rem 0 2rem;'>				<img src='/static/home/img/tan/show.png'>			</div>		</div>	</body></html>"
								
							  });
						}else if( newCount = 1 ){
							layer.open({
								content: "<!DOCTYPE><html>	<head>		<meta charset='utf-8'>		<meta name='viewport' content='width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0'>	</head>	<style>	 .layui-m-layercont{padding:0 !important;}	.jiangCon{	background:url('/static/home/img/tan/back.png') no-repeat center center fixed;background-size: cover;		margin:0 auto;		}		img{			max-width:100%;			margin:0 auto;			text-align:center;		}		.jiang,.jinlang,.chakan{			    text-align: center;		}	</style>	<body>		<div class='jiangCon'>			<div class='count' style='padding-top:2rem;'>				<img src='/static/home/img/tan/one.png'>			</div>			<div class='jiang' style='padding: 2rem 0;'>				<img src='"+jiangImg+"'>			</div>			<div class='jinlang'>				<img src='/static/home/img/tan/jinlangbutton.png' onclick='bankJiangPin()'>			</div>			<div class='chakan' style='padding:1rem 0 2rem;'>				<img src='/static/home/img/tan/show.png'>			</div>		</div>	</body></html>"
								
							  });
						}
						
				
				}else{
					//否则没有抽奖次数
					localStorage.setItem("choujiangCount",0);
					layer.open({
								content: "<!DOCTYPE><html>	<head>		<meta charset='utf-8'>		<meta name='viewport' content='width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0'>	</head>	<style>	 .layui-m-layercont{padding:0 !important;}	.jiangCon{	background:url('/static/home/img/tan/back.png') no-repeat center center fixed;background-size: cover;		margin:0 auto;		}		img{			max-width:100%;			margin:0 auto;			text-align:center;		}		.jiang,.jinlang,.chakan{			    text-align: center;		}	</style>	<body>		<div class='jiangCon'>			<div class='count' style='padding-top:2rem;'>				<img src='/static/home/img/tan/zone.png'>			</div>			<div class='jiang' style='padding: 2rem 0;'>				<img src='"+jiangImg+"'>			</div>			<div class='jinlang'>				<img src='/static/home/img/tan/jinlangbutton.png' onclick='bankJiangPin()'>			</div>			<div class='chakan' style='padding:1rem 0 2rem;'>				<img src='/static/home/img/tan/show.png'>			</div>		</div>	</body></html>"
								
					});
				}
			}else{
				//layer.alert(data.message)
				layer.open({
					content: data.message
					,btn: '我知道了'
				  });
			}
		}
		
	})
	
}






//抽奖
function choujiang1(){
	var is_user = 1;
	var count = localStorage.getItem("choujiangCount");
	if( count <= 0){
		layer.open({
			content: '没有抽奖次数了！'
			,btn: '我知道了'
		  });
		return;
	}
	var loding = layer.open({
		type: 2
		,content: '加载中'
	  });
	$.ajax({
		url:'/home/choujiang',
		type:'post',
		dataType:'json',
		data:{is_user:is_user},
		success:function( data  ){
			layer.close(loding);
			if( data.code == 0 ){
				if( count > 1 ){
					//可以继续抽奖
					var newCount = count - 1;
					localStorage.setItem("choujiangCount",newCount);
					
					/*layer.confirm('恭喜您抽中“'+data.data.name+'”', {
					  btn: ['继续抽奖','去查看'] //按钮
					}, function(){
					  choujiang();
					}, function(){
					  window.location.href = "/home/jiangping.html";
					});*/
					//询问框
					  layer.open({
						content: '恭喜您抽中“'+data.data.name+'”'
						,btn: ['继续抽奖', '去查看']
						,yes: function(index){
						  choujiang();
						},no:function(index){
							window.location.href = "/home/jiangping.html";
						}
					  });
				}else{
					//否则没有抽奖次数
					localStorage.setItem("choujiangCount",0);
					/*layer.confirm('恭喜您抽中“'+data.data.name+'”', {
					  btn: ['去查看'] //按钮
					},  function(){
					  window.location.href = "/home/jiangping.html";
					});*/
					layer.open({
						content: '恭喜您抽中“'+data.data.name+'”'
						,btn: ['去查看']
						,yes: function(index){
						   window.location.href = "/home/jiangping.html";
						}
					  });
				}
			}else if( data.code == 2 ){
				if( count > 1 ){
					//可以继续抽奖
					var newCount = count - 1;
					localStorage.setItem("choujiangCount",newCount);
					
					/*layer.confirm('恭喜您抽中“'+data.data.name+'”', {
					  btn: ['继续抽奖','去查看'] //按钮
					}, function(){
					  choujiang();
					}, function(){
					  window.location.href = "/home/jiangping.html";
					});*/
					//询问框
					  layer.open({
						content: '谢谢参与'
						,btn: ['继续抽奖']
						,yes: function(index){
						  choujiang();
						},no:function(index){
							window.location.href = "/home/jiangping.html";
						}
					  });
				}else{
					//否则没有抽奖次数
					localStorage.setItem("choujiangCount",0);
					/*layer.confirm('恭喜您抽中“'+data.data.name+'”', {
					  btn: ['去查看'] //按钮
					},  function(){
					  window.location.href = "/home/jiangping.html";
					});*/
					layer.open({
						content: '谢谢参与'
						,btn: '我知道了'
					  });
				}
			}else{
				//layer.alert(data.message)
				layer.open({
					content: data.message
					,btn: '我知道了'
				  });
			}
		}
		
	})
	
}

function Chater() {
    var self = this;
    this.started = -1;
    this.jData;
    this._score = 0;
    this._goto = 0;
    this._path = "ques/";
    this.personNum = 0;
    this.personID = 0;
    this.myPhoto = "";
    this.myName = "";
    this.message_queue = [];
    this.cir;
    this.endkeys = [];
    this.wxuser;
    this.shareurl;
    this.voiceID = 0;
    this.replaceName = function(content, name) {
        if (typeof content == 'object') {
            return content
        }
        return content.replace(/\[name\]/g, name)
    }
    this.replaceChatImg = function(message) {
        if (typeof message == 'object') {
            return message
        }
        var patt = new RegExp(/\[img.*f='(.*?)'\]/g);
        var res = patt.exec(message);
        if (res != null) {
            message = "<img src='./ques/" + self.personID + "/" + res[1] + "' style='width:100%'/>"
        }
        return message
    }
    this.replaceChatVoice = function(message) {
        if (typeof message == 'object') {
            return message
        }
        var patt = new RegExp(/\[voice.*f='(.*?)'\]/g);
        var res = patt.exec(message);
        if (res != null) {
            var a = eval('vc' + res[1]);
            message = '<div id="v' + self.voiceID + '" vc="vc' + res[1] + '" class="voice-bar"><img src="./img/voice.png"/></div>';
            $('#v' + self.voiceID).css('width', a.duration * 15 + 'px');
            self.voiceID++;
            console.log("Playing " + a.src + ", for: " + a.duration + "seconds.")
        }
        return message
    }
    this.voiceBarListener = function() {
        $('.voice-bar').off('click').click(function() {
            self.audioPlay('da');
            var a = eval($(this).attr('vc'));
            a.currentTime = 0;
            a.play();
            $(this).css('border-left', '0')
        })
    }
    this.randomAnswers = function(data) {
        var arr = data;
        var rel = [];
        for (; rel.length < 3;) {
            var idx = Math.floor(Math.random() * arr.length);
            rel.push(arr[idx]);
            arr.splice(idx, 1)
        }
        return rel
    }
    this.photo = function(photo, id) {
        return "./" + self._path + id + "/" + photo
    }
    this.getMessage = function() {
        self.message_queue = [];
        var message = self.jData.Q[self._goto].que.text;
        var msgs = message.split('/');
        if (msgs.length > 0) {
            self.message_queue = msgs
        } else {
            self.message_queue[0] = message
        }
    }
    this.getChatPhoto = function() {
        var photo = self.jData[self.jData.Q[self._goto].que.person].photo;
        return self.photo(photo, self.personID)
    }
    this.drawHint = function(text) {
        var hint = $('#ui-templates').find('.chat-hint').clone();
        var text = self.replaceName(text, self.myName);
        text = text.replace(/[\/]/g, '<br/>');
        text = text.replace(/\[img.*f='(.*?)'\]/g, '<img onclick=\'choujiang()\' src="ques/' + self.personID + '/$1" />');
        console.log(text);
        if (self.personID == 0) {
            text = text.replace('网易联通', '<a href="http://love.163.com/app?from=coschatfemale">网易联通</a>')
        } else if (self.personID == 1) {
            text = text.replace('网易联通', '<a href="http://love.163.com/app?from=coschatmale">网易联通</a>')
        }
        hint.html(text);
        hint.appendTo($('#main'))
    }
    this.drawChat = function(side, photo, content, score) {
        var div = $("#ui-templates").find(".chat-cell-" + side).clone();
        var text = self.replaceName(content, self.myName);
        div.find(".chat-content").html(text);
        div.find(".info-img").attr("src", photo);
        div.appendTo($('#main'));
        $("html, body").animate({
            scrollTop: $(document).height()
        },
        300);
        if (score != '' && side == 'right') {
            self.scoreMotion(div, score)
        }
        return div
    }
    this.replaceChatContent = function(chatobj, content) {
        chatobj.find('.chat-content').html(content);
        $("html, body").animate({
            scrollTop: $(document).height()
        },
        300)
    }
    this.drawAnswer = function() {
        $('#panel').empty();
        $('#panel').hide();
        var rel = self.randomAnswers(self.jData.Q[self._goto].ans);
        $.each(rel,
        function(k, v) {
            var ans = $("#ui-templates").find(".ans-cell").clone();
            ans.attr("score", v.score);
            ans.attr("goto", v.goto);
			
            var text = self.replaceName(v.text, self.myName);
            ans.html(text);
            $('#panel').append(ans);
            ans.click(function() {
                $('#panel').empty();
                $('#panel').hide();
                $('#panel-faker').height(0);
                self.drawChat('right', self.myPhoto, $(this).html(), parseInt($(this).attr('score')));
                self.countScore($(this));
                self.audioPlay('da')
            })
        });
        $('#panel-faker').height($('#panel').height());
        $('#panel').show();
        $("html, body").animate({
            scrollTop: $(document).height()
        },
        200)
    }
    this.showEnd = function() {
        var idx = 0;
        var ends = ['s', 'b', 'c', 'f'];
        var hint = '';
        $.each(self.endkeys,
        function(key, val) {
            if (self._score < val) {
                console.log('val:' + val);
                idx++
            }
            if (self._score < 60) {
                //var d = Math.floor(Math.random() * self.jData.end0.length);
                hint = self.jData.end0[0]
				localStorage.setItem("choujiangCount", "1");//抽奖次数
            } else if (self._score == 100) {
                //var d = Math.floor(Math.random() * self.jData.end0.length);
                hint = self.jData.end0[2]
				localStorage.setItem("choujiangCount", "3");//抽奖次数
            } else {
                hint = self.jData.end0[1]
				localStorage.setItem("choujiangCount", "2");//抽奖次数
            }
        });
        console.log('score:' + self._score);
        console.log('idx:' + idx);
        console.log('ends[idx]:' + ends[idx]);
        var e = $('#ui-templates').find('.end-container').clone().appendTo($('#main'));
        e.find('.end-line').attr('class', 'end-line end' + ends[idx] + '-line');
        e.find('.e-score').attr('class', 'e-score score-' + self._score);
        e.find('.e-fen').attr('class', 'e-fen ' + ends[idx] + '-fen');
        e.find('.end-line').attr('class', 'end-line end' + ends[idx] + '-line');
        e.find('.end-text').attr('class', 'end-text ' + ends[idx] + '-text');
		console.log(hint)
        self.drawHint(hint)
    }
    this.showEndBtn = function() {
        $('#ui-templates .end-btn').clone().appendTo($('#panel'));
        $('#panel-btn').hide();
        $('#panel').show();
        $('#re-chat').off('click').click(function() {
            self.getJson(self.personID);
            self.audioPlay('da')
        });
        $('#re-select').off('click').click(function() {
            self.init();
            $.mobile.changePage($('#info'), 'none');
            self.audioPlay('da')
        });
        $("html, body").animate({
            scrollTop: $(document).height()
        },
        200)
    }
    this.ifgo = function(go) {
        self._goto = go;
        var go_if = go.split(';');
        if (go_if.length > 1) {
            $.each(go_if,
            function(k, v) {
                var g = v.split(',');
                console.log("_score:" + self._score);
                console.log("_g[0]:" + g[0]);
                console.log("_g[1]:" + g[1]);
                if (self._score <= g[0]) {
                    self._goto = g[1]
                }
            })
        }
    }
    this.countScore = function(ans) {
        var go = ans.attr('goto');
        var score = parseInt(ans.attr('score'));
        self._score += score;
        if (self._score > 100) {
            self._score = 100
        }
        if (self._score <= 0) {
            self._score = 0
        }
        console.log("go:" + go);
        if (go.substr(0, 3) == "pop") {
            console.log('popup');
            popup(self.personID, self.jData.p0.name);
            var a = new Audio("./ques/" + self.personID + "/" + go + ".mp3");
            a.addEventListener('loadedmetadata',
            function() {
                roleVoiceMp3 = a;
                $('#chat-open').off('click').click(function() {
                    if ($(this).attr('isclick') == 'none') {
                        $('.voice-play').show();
                        $(this).attr('src', 'img/calloff.png');
                        $(this).attr('isclick', 'yes');
                        $('#chat-open').removeClass('rotate-shack');
                        roleVoiceMp3.play()
                    } else {
                        $(this).attr('isclick', 'none');
                        $(this).attr('src', 'img/callon.png');
                        $('.voice-play').hide();
                        $('#match-popup').hide();
                        $('#match-container').hide();
                        roleVoiceMp3.pause();
                        roleVoiceMp3.currentTime = 0;
                        roleVoiceMp3 = null;
                        if (self.personID == 0) {
                            console.log('personid==0');
                            self.ifgo("100,28;70,29;40,30")
                        } else {
                            console.log('personid==1');
                            self.ifgo("100,24;70,23;40,22")
                        }
                        console.log("personID:" + self.personID);
                        console.log("goto:" + self._goto);
                        self.goChat()
                    }
                })
            });
            return
        }
        if (go == '') {
            self._goto++
        } else {
            self.ifgo(go)
        }
        self.changeEmotion();
		console.log(self._score)
		console.log('_goto:' + self._goto)
		if( score == 0 ){
			self._goto = 6;
		}
        if (self._goto < self.jData.Q.length) {
            self.goChat()
        } else {
            self.showEnd();
            self.showEndBtn()
        }
    }
    this.changeEmotion = function() {
        self.cir.to = 1 + self._score / 100;
        if (self._score < 30) {
            $('#circle-photo div').attr('class', 'person-motion-0')
        } else if (self._score > 20 && self._score < 80) {
            $('#circle-photo div').attr('class', 'person-motion-1')
        } else {
            $('#circle-photo div').attr('class', 'person-motion-2')
        }
    }
    this.scoreMotion = function(div, score) {
       /* var obj = $('#get-point');
        var css = 'get-point-0';
        if (score < 0) {
            css = 'get-point-1'
        }
        if (score < -90) {
            css = 'get-point-2'
        }
        obj.find('div').attr('class', css);
        obj.show();
        obj.css({
            'top': div.offset().top,
            'opacity': 1
        });
        obj.animate({
            'top': '-=80',
            'opacity': 0
        },
        1200,
        function() {
            obj.hide()
        })*/
    }
    this.showLeftChat = function() {
        document.title = '对方正在输入...';
        var loading = $('#ui-templates .sk-three-bounce').clone();
        var chatobj = self.drawChat('left', self.getChatPhoto(), loading);
        $('#main').find(".chat-readed").show();
        setTimeout(function() {
            self.audioPlay('xiu');
            var message = self.replaceChatImg(self.message_queue[0]);
            var message = self.replaceChatVoice(self.message_queue[0]);
			
            var text = self.replaceName(message, self.myName);
			text = text.replace('www.baidu.com', '<a style="word-wrap: break-word;" href="http://t.cn/R3CXxP3">http://t.cn/R3CXxP3</a>')
			text = text.replace('www.akuan.com', '<a style="word-wrap: break-word;" href="http://t.cn/R3Ca15B">http://t.cn/R3Ca15B</a>')
			text = text.replace('www.akuan1.com', '<a style="word-wrap: break-word;" href="http://t.cn/R3aTPIl">http://t.cn/R3aTPIl</a>')
			text = text.replace('www.akuan2.com', '<a style="word-wrap: break-word;" href="http://t.cn/R3CSCyj">http://t.cn/R3CSCyj</a>')
            self.replaceChatContent(chatobj, text);
			
            self.message_queue.splice(0, 1);
            document.title = self.jData.p0.name;
			console.log('111:'+self.jData.Q[self._goto].que.goto)
            if (self.message_queue.length > 0) {
                self.showLeftChat()
            } else {
				if( self.jData.Q[self._goto].que.goto == 99){
					console.log('222:'+self.jData.Q[self._goto].que.goto)
					self.showEnd();
					self.showEndBtn()
				}
                self.toggleReady()
            }
			
            self.voiceBarListener()
			
        },
        700)
    }
    this.goChat = function() {
        console.log('goto:' + self._goto);
        if (self.jData.Q[self._goto].ans.length < 1) {
            self.drawHint(self.jData.Q[self._goto].que.text);
            console.log('is hint goto :' + self.jData.Q[self._goto].que.goto);
            if (self.jData.ans[self._goto].que.goto == "") {
                self._goto++
            } else {
                self.ifgo(self.jData.Q[self._goto].que.goto)
            }
            self.getMessage();
            setTimeout(function() {
                self.showLeftChat()
            },
            1300)
        } else {
            self.getMessage();
            self.showLeftChat()
        }
    }
    this.toggleWait = function() {
        $('#toggle').addClass("ui-state-disabled");
        $('#toggle').html('...')
    }
    this.toggleReady = function() {
        $('#toggle').removeClass('ui-state-disabled');
        $('#toggle').html('选择回复内容...')
    }
    this.audioPlay = function(audio) {
        if (audio == "xiu") {
            EFxiu.currentTime = 0;
            EFxiu.play()
        } else if (audio == "da") {
            EFda.currentTime = 0;
            EFda.play()
        }
    }
    this.init = function() {
        console.log('init game...');
        self._goto = 0;
        self._score = 0;
        self.toggleWait();
        $('#loss-point').css({
            top: 0
        });
        $('#get-point').css({
            top: 0
        });
        $('#main').empty();
        $('#panel').empty();
        $('#panel').hide();
        $('#panel-btn').show();
        self.cir = new Circler();
        self.cir.radii = 42;
        self.cir.x = self.cir.y = 50;
        self.cir.init();
        self.cir.motion();
        self.cir.to = 1.99
    }
    this.getEnd = function() {
        self.endkeys = [];
        $.each(self.jData.end,
        function(key, val) {
            self.endkeys.push(key)
        });
        self.endkeys.sort(function(a, b) {
            return b - a
        })
    }
    this.start = function() {
		localStorage.setItem("choujiangCount",0);
        self.started = 1;
        self.init();
        self.getEnd();
        self.goChat();
        self.changeEmotion();
        $('#toggle').off('click').click(function() {
            self.drawAnswer();
            self.audioPlay('da');
            self.toggleWait();
            $("html, body").animate({
                scrollTop: $(document).height()
            },
            200)
        });
        $('#circle-photo div').css("background-image", "url('ques/" + self.personID + "/motion.png')")
    }
    this.getJson = function(num) {
        var file = num + "/qa.json";
        $.getJSON(this._path + file).done(function(json) {
            self.jData = json;
            self.start()
        }).fail(function(qxhr, textStatus, error) {
            var err = textStatus + ", " + error;
            console.log("Request Failed: " + err)
        })
    }
}